﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace RestCall
{
	public class Rest : IRest
	{
		public enum DataType{xml,json}
		
		/// <summary>
        /// Make raw call to server
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
		public Stream RestCall(string url)
		{
		    WebRequest request = WebRequest.Create(url);
		    WebResponse response = request.GetResponse();

		    return response.GetResponseStream();
		}

		/// <summary>
        /// Make REST call, deserialize and return
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="url"></param>
		/// <param name="dataType"></param>
		/// <returns></returns>
		public T RestCall<T>(string url, DataType dataType)
		{
			//Make call
            Stream data = this.RestCall(url);
			
			ISerializer deserialize;
			//Deserialize
			switch(dataType)
			{
				case DataType.json:
					deserialize = new XmlSerializer();
					break;
				case DataType.xml:
					deserialize = new JsonSerializer();
					break;
				default:
					deserialize = new JsonSerializer();
					break;
			}

            return deserialize.Deserialize<T>(data);
		}
	}
}
